//
//  TravenoteTableViewController.m
//  Travelmemory
//
//  Created by lanou3g on 16/3/25.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "TravenoteTableViewController.h"
#import "TravelHelper.h"
#import "TraveNoteCell.h"
#import "TraveNoteModel.h"
#import "TravelDetilCell.h"
#import "UIImageView+WebCache.h"
#import "MapViewController.h"
#import "TravePictureViewController.h"

#define kScreenW self.view.frame.size.width
static CGFloat cellHeight; // Cell的自适应高度
static CGFloat picHeight; // 图片的自适应高度

@interface TravenoteTableViewController ()

@property(nonatomic,strong)NSMutableArray *allModelArray;
// 存放所有的图片
@property (nonatomic, strong) NSMutableArray *allPicArray;
@end

@implementation TravenoteTableViewController

#pragma mark - 懒加载
- (NSMutableArray *)allModelArray {
    if (!_allModelArray) {
        self.allModelArray = [NSMutableArray array];
    }
    return _allModelArray;
}
- (NSMutableArray *)allPicArray {
    if (!_allPicArray) {
        self.allPicArray = [NSMutableArray array];
    }
    return _allPicArray;
}

- (void)viewWillAppear:(BOOL)animated{

    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.allModelArray = [NSMutableArray array];
    self.allPicArray = [NSMutableArray array];
    
    self.navigationItem.title = self.recommendModel.name;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(dismissAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStyleDone target:self action:@selector(shareAction)];
    
    [self handleData:[NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints?gallery_mode=1&sign=e27ff5dd6cefbda2efc343868822d433", self.recommendModel.ID]];

    if (self.recommendid) {
        [self handleData:[NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints?gallery_mode=1&sign=e27ff5dd6cefbda2efc343868822d433", self.recommendid]];
    }
    
 

    //    xib的注册方法
    [self.tableView registerNib:[UINib nibWithNibName:@"TraveNoteCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ScheduleCell" bundle:nil] forCellReuseIdentifier:@"sched"];
     [self.tableView registerClass:[TravelDetilCell class] forCellReuseIdentifier:@"travelDetail"];
    
}


- (void)dismissAction {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)handleData:(NSString *)urlString{

    [[TravelHelper defaultTravelHelper] get:urlString params:nil success:^(id responseObj) {
//        NSLog(@"%@",urlString);
        for (NSDictionary *dic in responseObj[@"days"]) {
//            NSLog(@"%@",dic);
            for (NSDictionary *dict1 in dic[@"waypoints"]) {
//                NSLog(@"%@",dic);
                TraveNoteModel *model = [[TraveNoteModel alloc] init];
                [model setValue:responseObj[@"user"][@"name"] forKey:@"user_name"];
                [model setValuesForKeysWithDictionary:responseObj[@"user"]];
                [model setValuesForKeysWithDictionary:responseObj];
                [model setValuesForKeysWithDictionary:dic];
                [model setValuesForKeysWithDictionary:dict1];

                if ([dict1[@"location"] isKindOfClass:[NSDictionary class]]) {
                    [model setValuesForKeysWithDictionary:dict1[@"location"]];
                }
                if ([dict1[@"photo_info"] isKindOfClass:[NSDictionary class]]) {
                    [model setValuesForKeysWithDictionary:dict1[@"photo_info"]];
                }
                if ([dict1[@"poi"] isKindOfClass:[NSDictionary class]]) {
                    [model setValuesForKeysWithDictionary:dict1[@"poi"]];
                    [model setValue:dict1[@"poi"][@"name"] forKey:@"poi_name"];
                    if ([dict1[@"poi"][@"location"] isKindOfClass:[NSDictionary class]]) {
                        [model setValuesForKeysWithDictionary:dict1[@"poi"][@"location"]];
                    }
                }

                [self.allModelArray addObject:model];
//                NSLog(@"%@",self.allModelArray);
                // 保存有图片的Model
                if (![model.photo_s isEqualToString:@""]) {
                    [self.allPicArray addObject:model];
                }

            
            }
        }
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"数据解析失败");
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return 1;
    }
    return self.allModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
       
        TraveNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        if (self.allModelArray.count != 0) {
            
            TraveNoteModel *model = self.allModelArray[0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.titleLabel.text = model.name;
//            NSLog(@"%@",model.name);
            cell.TimeLabel.text = model.first_day;
            if (model.mileage > 1000) {
                cell.LengthLabel.text = [NSString stringWithFormat:@"%.2ld 万Km", model.mileage / 1000];
            }else {
                cell.LengthLabel.text = [NSString stringWithFormat:@"%03ldKm", (long)model.mileage];
            }
            [cell.HearderImageView sd_setImageWithURL:[NSURL URLWithString:model.trackpoints_thumbnail_image]];
            ;
            cell.iconImageView.layer.masksToBounds = YES;
            cell.iconImageView.layer.cornerRadius = cell.iconImageView.frame.size.width / 2;
            [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar_l] placeholderImage:[UIImage imageNamed:@"11"] options:SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
            }];
            cell.NameLabel.text = model.user_name;
            cell.LikeLabel.text = [NSString stringWithFormat:@"%@", model.recommendations];
            // 添加手势
            cell.HearderImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
            [cell.HearderImageView addGestureRecognizer:tap];

            
        }
        
        
        return cell;
        

    }else{
    
        TravelDetilCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travelDetail" forIndexPath:indexPath];
        if (self.allModelArray.count != 0) {
            TraveNoteModel *model = self.allModelArray[indexPath.row];
            if (model.h == nil) {
                // 当没有图片时返回图片的高度为0
                cell.imageV.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0);
                cell.contentLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.imageV.frame) + 10, [UIScreen mainScreen].bounds.size.width - 20, [self backHeight:model.text]);
                cell.contentLabel.text = model.text;
                cellHeight = [self backHeight:model.text] + 10;
                if (cellHeight == 0) {
                    cell.timeImageV.frame = CGRectMake(10, CGRectGetMaxY(cell.contentLabel.frame) + 5, 20, 0);
                    cell.timeLabel.frame = CGRectMake(CGRectGetMaxX(cell.timeImageV.frame), CGRectGetMinY(cell.timeImageV.frame), kScreenW * 0.3, 0);
                    cell.timeLabel.font = [UIFont systemFontOfSize:14];
                    cell.addressButton.frame = CGRectMake(CGRectGetMaxX(cell.timeLabel.frame), CGRectGetMinY(cell.timeLabel.frame), kScreenW * 0.7 - 30, 0);
                }
                
            }else {
                // 有图片时,使用宽高比实现返回不同的高度
                picHeight = [model.h intValue] * kScreenW / [model.w intValue];
                cell.imageV.frame = CGRectMake(10, 10, kScreenW - 20, picHeight - 30);
                //[cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.photo]];
                [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.photo_s] placeholderImage:[UIImage imageNamed:@"11"] options:SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                }];
                cell.contentLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.imageV.frame) + 5, kScreenW - 20, [self backHeight:model.text]);
                cell.contentLabel.text = model.text;
                cell.timeLabel.text = [model.local_time substringFromIndex:5];
                [cell.addressButton setTitle:model.poi_name forState:UIControlStateNormal];
                cell.timeImageV.frame = CGRectMake(10, CGRectGetMaxY(cell.contentLabel.frame) + 5, 20, 20);
                cell.timeImageV.image = [UIImage imageNamed:@"iconfont-shijian"];
                cell.timeLabel.frame = CGRectMake(CGRectGetMaxX(cell.timeImageV.frame), CGRectGetMinY(cell.timeImageV.frame), kScreenW * 0.3, 20);
                cell.timeLabel.font = [UIFont systemFontOfSize:14];
                cell.addressButton.frame = CGRectMake(CGRectGetMaxX(cell.timeLabel.frame), CGRectGetMinY(cell.timeLabel.frame), kScreenW * 0.7 - 30, 20);
                cellHeight = picHeight + [self backHeight:model.text] + 40;
            }
            
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }

        

    return nil;
}

#pragma mark - 手势
- (void)tapAction {
//    NSLog(@"跳转地图");
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.allModelArray = self.allModelArray;
    [self showViewController:mapVC sender:nil];
}

#pragma mark - Label自适应高度
- (CGFloat)backHeight:(NSString *)contentStr {
    
    return [contentStr boundingRectWithSize:CGSizeMake(kScreenW, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 380;
    }
    return cellHeight;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section != 0) {
   
        TravePictureViewController *travePictuerVC = [[TravePictureViewController alloc] init];
        TraveNoteModel *model = self.allModelArray[indexPath.row];
        if (model.h != nil) {
            travePictuerVC.page = [self.allPicArray indexOfObject:model];
            travePictuerVC.picArray = self.allPicArray;
            [self showViewController:travePictuerVC sender:nil];
        }
    }


}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
